package com.tg.demo.web;

import com.github.pagehelper.PageInfo;
import com.tg.demo.common.BarView;
import com.tg.demo.common.ConstantUtil;
import com.tg.demo.common.Page;
import com.tg.demo.common.Result;
import com.tg.demo.common.util.DateUtils;
import com.tg.demo.config.SysUserContext;
import com.tg.demo.entity.Activity;
import com.tg.demo.entity.ActivityItem;
import com.tg.demo.entity.ActivityRecord;
import com.tg.demo.entity.User;
import com.tg.demo.mapper.ActivityItemMapper;
import com.tg.demo.mapper.ActivityRecordMapper;
import com.tg.demo.service.ActivityService;
import com.tg.demo.service.UserService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

/**
 * IndexController
 *
 * @author yuanjin
 * @date 2019/3/21
 */
@Controller
@Slf4j
@RequestMapping("/activity")
public class ActivityController {

    @Resource
    private UserService userService;

    @Resource
    private ActivityService activityService;

    @Resource
    private ActivityItemMapper activityItemMapper;

    @Resource
    private ActivityRecordMapper activityRecordMapper;

    /**
     * 跳转到列表页
     *
     * @param model the model
     * @return string string
     */
    @RequestMapping(value = "/gotoListPage", method = {RequestMethod.GET, RequestMethod.POST})
    public String gotoListPage(Model model) {
        return "/activity/list";
    }

    @RequestMapping("/list")
    @ResponseBody
    public Page list(Page page, Activity activity) {
        User user = SysUserContext.getSysUser();
        if (user.getRole().equals(1)) {
            activity.setCreateUser(user.getUserCode());
        }
        PageInfo<Activity> info = activityService.getListByPage(activity, page.getPage(), page.getPageSize());
        Page result = new Page();
        result.setTotal(Integer.parseInt(info.getTotal() + ""));
        result.setRows(info.getList());
        return result;
    }

    @RequestMapping(value = "/edit")
    @ResponseBody
    public Result gotoEdit(Integer id) {
        Result result = new Result(0, "failed");
        Activity activity = activityService.getActivityById(id);
        result.setData(activity);
        result.setCode(1);
        return result;
    }

    @RequestMapping(value = "/add")
    @ResponseBody
    public Result gotoAdd(Integer id) {
        User user = SysUserContext.getSysUser();
        Result result = new Result(0, "failed");
        List<Activity> list = activityService.getListToUser(user.getUserCode());
        Activity activity = Activity.builder().build();
        for (Activity item : list) {
            if (id.equals(item.getId())) {
                activity = item;
                break;
            }
        }
        result.setData(activity);
        result.setCode(1);
        return result;
    }

    @RequestMapping(value = "/savePerson")
    @ResponseBody
    public Result savePerson(@ModelAttribute Activity activity) {
        User user = SysUserContext.getSysUser();
        Result result = new Result(ConstantUtil.FAILURE_CODE, ConstantUtil.FAILURE_MESSAGE);
        if (activity != null && null != activity.getId()) {
            ActivityRecord record = ActivityRecord.builder()
                    .userCode(user.getUserCode())
                    .userName(user.getUserName())
                    .activityId(activity.getId())
                    .itemId(activity.getItemId())
                    .createTime(new Date())
                    .id(activity.getRecordId())
                    .explainInfo(activity.getExplainInfo())
                    .build();
            if (null == activity.getRecordId()) {
                //新增记录
                activityService.insertRecord(record);
            } else {
                //更新
                activityService.updateRecord(record);
            }
            result = new Result(ConstantUtil.SUCCESS_CODE, ConstantUtil.SUCCESS_MESSAGE);
        }
        return result;
    }

    /**
     * 保存用户信息
     *
     * @param activity the user
     * @return object object
     */
    @RequestMapping(value = "/save")
    @ResponseBody
    public Result save(Activity activity) {
        User user = SysUserContext.getSysUser();
        Result result = new Result(ConstantUtil.FAILURE_CODE, ConstantUtil.FAILURE_MESSAGE);
        if (activity != null && null != activity.getItems() && !activity.getItems().isEmpty()) {
            activity.setCreateUser(user.getUserCode());
            if (null == activity.getId()) {
                activityService.insert(activity);
            } else {
                activityService.update(activity);
            }
            result = new Result(ConstantUtil.SUCCESS_CODE, ConstantUtil.SUCCESS_MESSAGE);
        }
        return result;
    }

    @RequestMapping(value = "/delete")
    @ResponseBody
    public Result delete(Integer id) {
        Result result = new Result(ConstantUtil.FAILURE_CODE, ConstantUtil.FAILURE_MESSAGE);
        Integer res = activityService.delete(id);
        if (res > 0) {
            result = new Result(ConstantUtil.SUCCESS_CODE, ConstantUtil.SUCCESS_MESSAGE);
        }
        return result;

    }

    /**
     * 跳转到列表页
     *
     * @param model the model
     * @return string string
     */
    @RequestMapping(value = "/view", method = {RequestMethod.GET, RequestMethod.POST})
    public String view(Model model, Integer id) {
        List<Activity> list = activityService.getListByCondition(
                Activity.builder().id(id).build()
        );
        Activity activity = list.get(0);
        User user = userService.getUserByUserCode(activity.getCreateUser());
        activity.setCreateUserName(user.getUserName());
        activity.setStartTimeStr(DateUtils.dateToStr(activity.getStartTime()));
        activity.setEndTimeStr(DateUtils.dateToStr(activity.getEndTime()));
        model.addAttribute("activity", activity);
        return "/activity/view";
    }

    @RequestMapping("/recordList")
    @ResponseBody
    public Page recordList(Page page, Activity activity) {
        ActivityRecord record = ActivityRecord.builder().activityId(activity.getId()).build();
        PageInfo<ActivityRecord> info = activityService.getRecordListByPage(record, page.getPage(), page.getPageSize());
        Page result = new Page();
        result.setTotal(Integer.parseInt(info.getTotal() + ""));
        result.setRows(info.getList());
        return result;
    }

    @RequestMapping("/recordView")
    @ResponseBody
    public Result recordView(Activity activity) {
        Result result = new Result(ConstantUtil.FAILURE_CODE, ConstantUtil.FAILURE_MESSAGE);
        if (null != activity && activity.getId() != null) {
            ActivityRecord record = ActivityRecord.builder().activityId(activity.getId()).build();
            List<ActivityRecord> records = activityRecordMapper.getListByCondition(record);
            List<ActivityItem> items = activityItemMapper.getListByCondition(
                    ActivityItem.builder().activityId(activity.getId()).build()
            );
            List<Object> keys = new ArrayList<>();
            List<Object> values = new ArrayList<>();
            for (ActivityItem ele : items) {
                keys.add(ele.getItemValue());
                int count = 0;
                for (ActivityRecord obj : records) {
                    if (obj.getItemId().equals(ele.getId())) {
                        count++;
                    }
                }
                values.add(count);
            }
            result = new Result(ConstantUtil.SUCCESS_CODE, ConstantUtil.SUCCESS_MESSAGE);
            result.setData(new BarView(keys, values));
        }
        return result;
    }
}
